package com.lizardmind.haofudoctor.ui.studio.serviceSetting

import android.arch.lifecycle.ViewModelProviders
import android.content.Context
import android.content.res.ColorStateList
import android.os.Bundle
import android.os.Handler
import android.support.v7.app.AlertDialog
import android.text.InputType
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.RadioButton
import android.widget.RadioGroup
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.SizeUtils
import com.blankj.utilcode.util.SpanUtils
import com.linxiao.framework.activity.BaseActivity
import com.linxiao.framework.util.color
import com.linxiao.framework.util.getDataBinding
import com.linxiao.framework.util.ke
import com.lizardmind.haofudoctor.R
import com.lizardmind.haofudoctor.databinding.ActivityChargeSettingBinding
import com.lizardmind.haofudoctor.manager.postApi
import com.lizardmind.haofudoctor.other.DoctorInfo
import com.lizardmind.haofudoctor.other.Request
import com.lizardmind.haofudoctor.other.formatToZY
import com.lizardmind.haofudoctor.other.jsonOf
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.activity_charge_setting.*
import kotlinx.android.synthetic.main.include_title_right_text.*
import org.jetbrains.anko.dialerFilter
import org.jetbrains.anko.forEachChild
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.jetbrains.anko.toast


/**
 * 收费设置 界面
 * Created by Extends on 2017/11/28 13:54
 */
class ChargeSettingActivity:BaseActivity() {
    private val binding by lazy { getDataBinding<ActivityChargeSettingBinding>(R.layout.activity_charge_setting) }
    private val vm by lazy {ViewModelProviders.of(ActivityUtils.getActivityList()[ActivityUtils.getActivityList().lastIndex-1] as BaseActivity).get(ServiceSettingVM::class.java) }
    private val rgList = arrayListOf<RadioButton>()
    private val supplement by lazy { intent.getStringExtra("supplement")?:"" }
    private val charges by lazy { intent.getStringExtra("charge")?:"" }
    private val rg by lazy { RadioButton(this).apply {
        layoutParams = RadioGroup.LayoutParams(RadioGroup.LayoutParams.MATCH_PARENT,SizeUtils.dp2px(50f))
        buttonDrawable = null
        background = null
        textSize = 16f
        setTextColor(ColorStateList(arrayOf(intArrayOf(-android.R.attr.state_checked),intArrayOf(android.R.attr.state_checked)),
                intArrayOf(color(R.color.gray3),color(R.color.stress))))
        setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.rb_charge_setting_right,0)
    } }
    private val edit by lazy { EditText(this).apply { inputType = InputType.TYPE_CLASS_NUMBER } }
    var i = false
    private var curPrice = ""
    private val dig by lazy {
        AlertDialog.Builder(this)
                .setTitle("自定义收费")
                .setView(edit)
                .setPositiveButton("确定"){ _, _ ->
                    val s = edit.text.toString()
                    if(s.isNotEmpty()){
                        changeDiy(s)
                    }
                }
                .setNegativeButton("取消"){_,_-> }
                .setOnDismissListener {
                    //延迟取消键盘
                    Handler().postDelayed({
                        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                        imm.hideSoftInputFromWindow(currentFocus.windowToken,
                                InputMethodManager.HIDE_NOT_ALWAYS)
                    },200)
                }
                .create()
    }
    override fun onCreatRootView(): View = binding.root

    override fun onInitView(savedInstanceState: Bundle?) {
        //初始化title
        imgLeft.setImageResource(R.mipmap.back)
        imgLeft.onClick { finish() }
        titleText.text = "服务设置"
        tvRight.text = "保存"
        tvRight.onClick {
            val charge = getChargeString()
            observe {
                postApi<Request<String>>(hashMapOf(
                        "action" to "edit_service",
                        "token" to DoctorInfo.token,
                        "data" to jsonOf(
                                "supplement" to binding.vm!!.supplement.get(),
                                "charge" to charge
                        ).formatToZY()
                ), Consumer {
                    it.dispose {
                        toast(it)
                        vm.charge.set(charge)
                        vm.supplement.set(binding.vm!!.supplement.get())
                    }
                })
            }
        }


        rgList.addAll((0 until acs_rg.childCount).map { acs_rg.getChildAt(it) }.filter { it is RadioButton }.map { it as  RadioButton})


        binding.apply {
            vm = ViewModelProviders.of(this@ChargeSettingActivity).get(ChargeSettingVM::class.java)
            lifecycle.addObserver(vm!!)
            vm!!.supplement.set(supplement)

            if(charges.isNotEmpty()){
                when(charges){
                    "0" -> rgList[0].isChecked = true
                    "20" -> rgList[1].isChecked = true
                    "50" -> rgList[2].isChecked = true
                    "100" -> rgList[3].isChecked = true
                    "200" -> rgList[4].isChecked = true
                    else -> {
                        changeDiy(charges)
                    }
                }
            }


            acsDiy.onClick {
                dig.show()
            }
            acsNote.text = SpanUtils()
                    .appendLine("说明：")
                    .appendLine("• 患者在填写问诊单时才需要支付咨询费").setForegroundColor(color(R.color.stress))
                    .appendLine("• 请在患者提交问诊单后24小时内处理问诊单，超时系统将自动退款")
                    .create()
        }
    }

    fun getChargeString():String{
        val i = rgList.indexOfFirst { it.isChecked }
        return when(i){
            0 -> "0"
            1 -> "20"
            2 -> "50"
            3 -> "100"
            4 -> "200"
            5 -> curPrice
            else -> "0"
        }
    }

    fun changeDiy(s:String){
        curPrice = s
        rg.text = getString(R.string.price_0,s)
        if(!i){
            acs_rg.addView(rg)
            rgList.add(rg)
            i=!i
        }
        rg.isChecked = true
    }
}